
const globalCache: any = {}
function queryString(key: string): string {
  if (!globalCache.url_queryString) {
    globalCache.url_queryString = {};
  }
  if (!globalCache.url_queryString[key]) {
    let url = window.location.hash;
    if (url.indexOf("?") === -1) {
      url = window.location.href.split("?").length > 1 ? window.location.href.split("?")[1] : "";
      url = "?" + url.split("#")[0];
    }
    const oRegex = new RegExp("[?&]" + key + "=([^&]+)", "i");
    const oMatch = oRegex.exec(url);
    if (oMatch && oMatch.length > 1) {
      const val = decodeURI(oMatch[1]);
      globalCache.url_queryString[key] = val;
      return val;
    } else {
      return "";
    }
  }
  return globalCache.url_queryString[key];
}

function queryObject(query?: string) {
  query = query || window.location.hash
  query = query.split("?").length > 1 ? query.split("?")[1] : ""
  if (!query) {
    query = window.location.href.split("?").length > 1 ? window.location.href.split("?")[1] : ""
    query = query.split("#")[0]
  }
  if (!query) {
    return {}
  }
  const reg = /([^=&\s]+)[=\s]*([^&\s]*)/g
  const obj:any = {}
  while (reg.exec(query)) {
    obj[RegExp.$1] = RegExp.$2
  }
  return obj
}

export default {
  queryString,
  queryObject
}
